package com.atstudying.mall.product.web;

import com.atstudying.mall.product.entity.CategoryEntity;
import com.atstudying.mall.product.service.CategoryService;
import com.atstudying.mall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author Mr.zhneg
 * @create 2020-10-29-0:12
 */
@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RedissonClient redissonClient;

    @GetMapping({"/","/index.html"})
    public String indexPage(Model model){

        //todo 1：查出所有的1级分类
        List<CategoryEntity> categoryEntities= categoryService.getLevel1Category();

        model.addAttribute("categorys",categoryEntities);
        return "index";
    }

    //以json格式返回
    @ResponseBody
    @GetMapping("/index/json/catalog.json")
    public  Map<String, List<Catelog2Vo>> getCatalogJson(){
        Map<String, List<Catelog2Vo>> indexJson=categoryService.getCatalogJson();
        return indexJson;
    }

    //以json格式返回
    //可重入锁
    @ResponseBody
    @GetMapping("/hello")
    public  String hello(){

        //可重入锁:1：获取一把锁，只要锁的名字一样，就是同一把锁
        RLock lock = redissonClient.getLock("my-lock");

        try {
            //2：加锁  阻塞式等待 拿不到锁就一直等，一直到拿到这个方法
            /**
             * 锁的自动续期，如果业务超长，运行期间自动给锁续上新的30s。不用担心业务时间长，锁自动过期被删除
             * 加锁的业务只要完成，就不会给当前锁续期。即使不手动解锁，锁默认在30s以后自动删除。都可以避免死锁的发生
             */
//            lock.lock();

            lock.lock(30, TimeUnit.SECONDS);//10s自动解锁，自动解锁时间一定要大于业务执行时间

            //问题：lock.lock(10, TimeUnit.SECONDS);在锁时间到了以后不会自动续期
            //1：如果我们传递了锁的的超时时间，就发送给redis执行脚本，进行占锁，默认超时就是我们指定时间
            //2：如果我们未指定锁的超时时间，就使用看门狗的默认时间
              //只要占锁成功，就会启动一个定时任务，【重新给锁设置过期时间，新的过期时间就是看门狗的默认时间】

            //最佳实战
            // lock.lock(10, TimeUnit.SECONDS);省掉了整个续期操作，手动解锁



            System.out.println("加锁成功，执行业务。。。。"+Thread.currentThread().getId());
            Thread.sleep(30000);
        }catch (Exception e){

        }finally {
            //3：解锁
            System.out.println("释放锁。。。。"+Thread.currentThread().getId());

            lock.unlock();
        }
        return "hello";
    }

    /**
     * 读写锁
     * @return
     */
    @GetMapping("/read")
    @ResponseBody
    public String writeValue(){
        RReadWriteLock lock=redissonClient.getReadWriteLock("rw-lock");
        //Returns the lock used for reading.
        RLock rlock1 = lock.readLock();
        rlock1.lock();

        Object s="";
        try {

            s =  redisTemplate.opsForValue().get("writeValue");

            System.out.println(s);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            rlock1.unlock();
        }

        return (String) s;
    }

    @GetMapping("/write")
    @ResponseBody
    public String readValue(){
        String s="";
        RReadWriteLock lock=redissonClient.getReadWriteLock("rw-lock");
        //Returns the lock used for writing.
        RLock rlock = lock.writeLock();

        try {

            //1：改数据加写锁，读数据加读锁
            rlock.lock();
            s= UUID.randomUUID().toString();
            Thread.sleep(30000);
            redisTemplate.opsForValue().set("writeValue",s);
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            rlock.unlock();
        }

        return s;
    }

    /**
     * 闭锁
     * 放假：锁门
     * 1班没人
     * 5个班全部走完，我们可以锁大门
     */
    @GetMapping("/lockDoor")
    @ResponseBody
    public String lockDoor() throws InterruptedException {

        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.trySetCount(5);
        door.await();//等待闭锁完成
        return "放假了";
    }

    @GetMapping("/gogogo/{id}")
    @ResponseBody

    public String gogogo(@PathVariable("id") Long id){
        RCountDownLatch door = redissonClient.getCountDownLatch("door");

        door.countDown();//计数加一
        return id+"班的人都走了。。。";
    }

    /**
     * 信号量
     * 3个
     * 车库停车
     */
    @GetMapping("/park")
    @ResponseBody
    public String park() throws InterruptedException {

        RSemaphore park = redissonClient.getSemaphore("park");
        park.acquire();//获取一个信号量，，获取一个值,,,占一个值
        return "ok";
    }

    @GetMapping("/go")
    @ResponseBody
    public String go() throws InterruptedException {

        RSemaphore park = redissonClient.getSemaphore("park");
        park.release();//释放一个车位
        return "ok";
    }
}
